﻿@page "/groups/{id}/{action}"
@inherits Fluxor.Blazor.Web.Components.FluxorLayout
@using Microsoft.EntityFrameworkCore;
@using SimpleIdServer.IdServer.Store;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.GroupStore;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;
@layout MainLayout
@inject DialogService dialogService
@inject NavigationManager navigationManager
@inject NotificationService notificationService
@inject IDispatcher dispatcher
@inject IGroupService groupService
@inject IState<GroupState> groupState

    <RadzenBreadCrumb>
        <RadzenBreadCrumbItem Path="/groups" Text="@Global.Groups" />
        <RadzenBreadCrumbItem Text="@Global.GroupDetails" />
    </RadzenBreadCrumb>

    <RadzenText class="mt-3 mb-3 no-margin" Text="@groupState.Value.Group?.Name" TextStyle="TextStyle.DisplayH3" />

    <RadzenBreadCrumb>
        @foreach (var groupName in groupNames)
        {
            <RadzenBreadCrumbItem Text="@groupName" />
        }
    </RadzenBreadCrumb>

<RadzenCardLoader Variant="Variant.Filled" IsLoading=@groupState.Value.IsLoading>
    <RadzenSplitter>
        <RadzenSplitterPane Size="10%">
            <RadzenTree Expand="@OnExpand" Data=@groups>
                <RadzenTreeLevel TextProperty="Name" Template="@treeTemplate" />
            </RadzenTree>
        </RadzenSplitterPane>
        <RadzenSplitterPane>
            <div class="ml-3">
                <RadzenTabs Change=@OnChange @bind-SelectedIndex="selectedIndex">
                    <Tabs>
                        <RadzenTabsItem Text="@Global.Children">
                            <GroupChildren Group="@groupState.Value.Group"></GroupChildren>
                        </RadzenTabsItem>
                        <RadzenTabsItem Text="@Global.Roles">
                            <GroupRoles Group="@groupState.Value.Group"></GroupRoles>
                        </RadzenTabsItem>
                    </Tabs>
                </RadzenTabs>
            </div>
        </RadzenSplitterPane>
    </RadzenSplitter>
</RadzenCardLoader>

@code {
    ICollection<SimpleIdServer.IdServer.Domains.Group> groups;
    RenderFragment<RadzenTreeItem> treeTemplate = (context) => builder =>
    {
        var grp = context.Value as SimpleIdServer.IdServer.Domains.Group;
        builder.OpenComponent<RadzenLink>(0);
        builder.AddAttribute(1, "Text", grp.Name);
        builder.AddAttribute(2, "Path", $"/groups/{grp.Id}/children");
        builder.CloseComponent();
    };

    Dictionary<string, int> mappingActionNameToIndex = new Dictionary<string, int>
    {
        { "children", 0 },
        { "roles", 1 }
    };

    [Parameter]
    public string id { get; set; } = null!;

    [Parameter]
    public string? action { get; set; } = null;

    public List<string> groupNames = new List<string>();

    int selectedIndex = 0;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender)
        {
            SubscribeToAction<SelectRealmSuccessAction>((act) =>
            {
                navigationManager.NavigateTo("/groups");
            });
            SubscribeToAction<GetGroupSuccessAction>((act) =>
            {
                groups.Add(act.RootGroup);
                groupNames = act.Group.FullPath.Split('.').ToList();
            });
            SubscribeToAction<AddGroupSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupMemberAdded });
                dialogService.Close();
                StateHasChanged();
            });
            SubscribeToAction<RemoveSelectedGroupsSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupMembersRemoved });
                StateHasChanged();
            });
            SubscribeToAction<RemoveSelectedGroupRolesSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupRolesRemoved });
            });
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (string.IsNullOrWhiteSpace(id)) return;
        if (!string.IsNullOrWhiteSpace(action) && mappingActionNameToIndex.ContainsKey(action))
            selectedIndex = mappingActionNameToIndex[action];
        SubscribeToAction<GetGroupFailureAction>((act) =>
        {
            notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = act.ErrorMessage });
            StateHasChanged();
        });
        dispatcher.Dispatch(new GetGroupAction { Id = id });
        groups = new List<SimpleIdServer.IdServer.Domains.Group>();
    }

    async Task OnExpand(TreeExpandEventArgs args)
    {
        var group = args.Value as SimpleIdServer.IdServer.Domains.Group;
        var children = group.Children;
        if (group.Children == null || !group.Children.Any())
        {
            var getResult = await groupService.Get(group.Id);
            children = getResult.Target.Children.ToList();
        }

        args.Children.Data = children;
        args.Children.Template = treeTemplate;
        args.Children.TextProperty = "Name";
        args.Children.HasChildren = (g) => true;
    }

    void OnChange(int index)
    {
        var rec = mappingActionNameToIndex.Single(kvp => kvp.Value == index);
        navigationManager.NavigateTo($"/groups/{id}/{rec.Key}");
    }
}